package cn.kgc.javaweb.servlet;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.javaweb.dto.UserPageDTO;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.enums.CodeMsg;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;
import cn.kgc.javaweb.util.JsonResultWriter;
import cn.kgc.javaweb.util.ResponseResult;

import javax.lang.model.element.VariableElement;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/11/9
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    // 获取验证码
    protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(140, 50, 4, 5);
        String code = lineCaptcha.getCode();
        req.getSession().setAttribute("code", code);

        ServletOutputStream outputStream = resp.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();

    }


    //登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取前端页面中发送的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");

        // 判定验证码是否正确

        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");

        //创建一个响应结果对象
        ResponseResult responseResult = new ResponseResult();

        if (code.equals(captcha)) {
            // 登录请求的验证
            try {
                User user = userService.login(username, password);
                if (user != null) {
                    responseResult.setMsg(CodeMsg.LOGIN_SUCCESS.getMsg());
                    responseResult.setCode(CodeMsg.LOGIN_SUCCESS.getCode());
                    // 将登录成功的用户信息存入 session 用于后续的非法请求的验证
                    req.getSession().setAttribute("user", user);
                    JsonResultWriter.writerJson(resp, responseResult);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        responseResult.setMsg(CodeMsg.LOGIN_FAIL.getMsg());
        responseResult.setCode(CodeMsg.LOGIN_FAIL.getCode());
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 用户信息分页查询  查询所有用户信息分页    搜索用户信息分页
    protected void selectPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        String searchParams = req.getParameter("searchParams");


        UserPageDTO userPageDTO = UserPageDTO.builder().limit(limit).page(page).searchParams(searchParams).build();
        ResponseResult responseResult = userService.selectPage(userPageDTO);
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 根据id 查询用户信息
    protected void selectById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        ResponseResult responseResult = userService.selectById(id);
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 修改用户信息
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // json 字符串
        String user = req.getParameter("user");
        User usr = JSONUtil.toBean(user, User.class);
        System.out.println("usr = " + usr);

        ResponseResult responseResult = userService.update(usr);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 添加用户信息
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String user = req.getParameter("user");
        User usr = JSONUtil.toBean(user, User.class);
        System.out.println("usr = " + usr);
        ResponseResult responseResult = userService.add(usr);
        JsonResultWriter.writerJson(resp, responseResult);
    }

    // 删除用户信息
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String ids = req.getParameter("ids");

        ResponseResult responseResult =  userService.delete(ids);
        JsonResultWriter.writerJson(resp, responseResult);


    }


    // 退出登录
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        ResponseResult responseResult = ResponseResult.builder().build();
        try {
            req.getSession().invalidate();
            responseResult.setMsg("退出登录,页面即将跳转");
            responseResult.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setMsg("退出失败");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);
    }

    //修改密码
    protected void changePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        // 获取相关参数  old_password  new_password  again_password
        String oldPassword = req.getParameter("old_password");
        String newPassword = req.getParameter("new_password");

        // 判定用户的旧密码是否正确
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String password = user.getPassword();

        ResponseResult responseResult = new ResponseResult().builder().build();

        if(password.equals(SecureUtil.md5(oldPassword))){
            // 调用业务层  更新用户密码
            responseResult =  userService.updatePwdById(newPassword,user.getId());
        }else {
            responseResult.setMsg("原始密码不正确");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);
    }


}
